package jTopaz;

import org.globus.ftp.GridFTPClient;
import java.io.File;
import org.globus.ftp.FileRandomIO;
import java.io.RandomAccessFile;

/**
Class that handles the actual execution of an upload.  Uses the GridFTPClient extendedPut() method.
*/
public class UploadThread extends Thread {

	private GridFTPClient client;
	
	private File localFile;
	private String remoteFileName;
	
	private RandomAccessFile localFileRA;
	private FileRandomIO source;
	
	private boolean complete;
	
	/**
	Creates a new UploadThread object.
	@param client the client that will be doing the actual transfer.
	@param localFile the file that will be uploaded
	@param remoteFileName the name of the destination file
	*/
	public UploadThread(GridFTPClient client, File localFile, String remoteFileName) {
	
		try {
			this.client = client;
			this.localFile = localFile;
			this.remoteFileName = remoteFileName;
		
			localFileRA = new RandomAccessFile(this.localFile, "r");
			source = new FileRandomIO(localFileRA);
			complete = false;	
		}
		
		catch (Exception e) {
			System.out.println(e);
		}
	}
	
	/**
	The actual execution of the upload
	*/
	public void run() {
	
		try {
			
			//if the file already exists, delete it
			client.setPassive();
			client.setLocalActive();
			if (client.exists(remoteFileName)) {
				System.out.println("deleting the file");
				client.deleteFile(remoteFileName);				
				}
				
				client.setPassive();
				client.setLocalActive();
				client.extendedPut(remoteFileName, source, null);
				//client.put(localFile, remoteFileName, false);
				complete = true;	
		}
		
		catch (Exception e) {
			System.out.println(e);
			e.printStackTrace();
		}	
	}
	
	/**
	Returns whether or not that upload has completed.
	*/
	public boolean transferComplete() {
		return complete;	
	}
}